<template>
    <div class="goods-add-form">
        <div class="section">
            <h2 class="section-title">修改入库单</h2>
            <el-form ref="ruleFormRef" style="max-width: 1200px;margin: 20px;" :model="othwr_order" status-icon
                :rules="rules" label-width="auto" class="demo-ruleForm">
                <el-form-item label="入库单号" prop="othwr_code">
                    <el-input v-model="othwr_order.othwr_code" readonly />
                </el-form-item>
                <div style="display: flex; justify-content: space-between;">
                    <div style="width: 48%;">
                        <el-form-item label="入库类型" prop="othwr_type" style="margin-bottom: 30px;">
                            <el-select v-model="othwr_order.othwr_type" placeholder="请选择入库类型"
                                @change="handleSelecttype">
                                <el-option v-for="item in options" :key="item.dict_value" :label="item.dict_label"
                                    :value="item.dict_value" class="option-style" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="入库库区" prop="zone_code" style="margin-bottom: 30px;">
                            <el-select v-model="othwr_order.zone_name" placeholder="请选择入库库区" @change="handleSzone">
                                <el-option v-for="item in Warhouse_zone" :key="item.zone_code" :label="item.zone_name"
                                    :value="item.zone_code" />
                            </el-select>
                        </el-form-item>
                    </div>

                    <div style="width: 48%;">
                        <!-- 移除关联单号表单项 -->





                        <el-form-item label="入库仓库" prop="warehouse_code" style="margin-bottom: 30px;">
                            <el-select v-model="othwr_order.warehouse_code" placeholder="请选择入库仓库"
                                @change="handleSelectChange">
                                <el-option v-for="item in Weahouse" :key="item.warehouse_code"
                                    :label="item.warehouse_name" :value="item.warehouse_code" />
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
            </el-form>
        </div>

        <div class="section">
            <h2 class="section-title">入库产品明细</h2>
            <div style="float: left;margin: 10px 0px;">
                <el-button type="primary" @click="productAdd">添加</el-button>
                <el-button @click="productDel">移除</el-button>
            </div>
            <el-table :data="selectedData" border style="width: 100%" :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{
                    textAlign: 'center',
                    background: '#f5f7fa',
                    fontWeight: 'bold',
                    position: 'sticky',
                    top: 0
                }" ref="selectedTable" @selection-change="handleSelectedChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="stock_name" label="货品名称" fixed="left" width="100" />
                <el-table-column prop="pro_code" label="货品编号" width="150" />
                <el-table-column prop="pro_brand" label="品牌" width="100" />
                <el-table-column prop="stock_model" label="规格型号" width="100" />
                <el-table-column prop="dict_code" label="单位" width="70">
                    <template #default="scope">
                        <span>{{ measureValue(scope.row.dict_code) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="location_code" label="入库库位" width="130">
                    <template #default="scope">
                        <el-select v-model="scope.row.location_name" placeholder="选择库位" size="small"
                            :disabled="isDisabledlocation" @change="(val) => locationEndit(val, scope.row)">
                            <el-option v-for="item in Warehouse_location" :key="item.location_code"
                                :label="item.location_name" :value="item.location_code" />
                        </el-select>
                    </template>
                </el-table-column>
                <!-- <el-table-column prop="stock_numder" label="当前库存" width="150" /> -->
                <el-table-column prop="inventory_numder" label="未入库数量" width="100" />


                <el-table-column prop="address" label="入库数量" width="90">
                    <template #default="scope">
                        <el-input v-model="scope.row.sale_qty" style="width: 75px" :precision="2" :min="0" />
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="入库单价" width="90">
                    <template #default="scope">
                        <el-input v-model="scope.row.pro_sale_price" style="width: 75px" :precision="2" :min="0" />
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="入库总金额" width="100">
                    <template #default="scope">
                        <span>{{ scope.row.pro_total_amount }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="pro_cost_price" label="成本金额" width="90" />
                <el-table-column prop="address" label="成本合计" width="90">
                    <template #default="scope">
                        <span>{{ scope.row.pro_total_cost }}</span>
                    </template>
                </el-table-column>
            </el-table>
            <div style="height: 40px; line-height: 40px;">
                <div style="display: inline-block; float: left;">合计</div>
                <div style="display: inline-block; float:right">入库总数量：{{ sale_total_qty }}
                    &nbsp;&nbsp;&nbsp; 入库总金额：{{ Number(sale_total_price).toFixed(2) }}
                    &nbsp;&nbsp;&nbsp;入库产品成本总额：{{ Number(cost_total_proce).toFixed(2) }}
                </div>
            </div>
        </div>

        <div class="button-group" style="position: absolute; bottom: 10px; right: 60.8px; display: flex; gap: 10px;">
            <el-button type="primary" @click="handleUpdate">保存修改</el-button>
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>

    <!-- 添加产品模态框 -->
    <el-dialog v-model="dialogTableVisible" width="800" title="添加产品">
        <hr>
        <div style="margin: 10px 0px;">
            <div style="float: left;margin: 10px 0px;">
                <el-input v-model="productName" style="width: 240px;margin-right: 20px;" placeholder="请输入货品编号/名称" />
                <el-select v-model="dict_code" placeholder="请选择单位" style="width: 240px">
                    <el-option v-for="item in measureOptios" :key="item.dict_value" :label="item.dict_label"
                        :value="item.dict_value" />
                </el-select>
            </div>
            <div style="float: right;margin: 10px 0px;">
                <el-button @click="productReaslt">重置</el-button>
                <el-button type="primary" @click="productEedit">查询</el-button>
            </div>
        </div>
        <el-table ref="multipleTableRef" :data="productData" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
                textAlign: 'center',
                background: '#f5f7fa',
                fontWeight: 'bold',
                position: 'sticky',
                top: 0
            }" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" :selectable="isDisabled" />
            <el-table-column property="pro_code" label="货品编号" width="180" />
            <el-table-column property="stock_name" label="货品名称" width="200" />
            <el-table-column property="stock_model" label="规格型号" />
            <el-table-column property="dict_code" label="单位">
                <template #default="scope">
                    <span>{{ measureValue(scope.row.dict_code) }}</span>
                </template>
            </el-table-column>
            <el-table-column property="pro_cost_price" label="入库单价" />
            <el-table-column property="stock_numder" label="当前库存" />
        </el-table>
        <br>
        <div style="text-align: center;display: flex; justify-content: center;">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
                :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="pageCount"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" size="small" />
        </div>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogTableVisible = false">取消</el-button>
                <el-button type="primary" @click="handleConfirmSelection">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, inject, watch, toRaw } from 'vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useWarehouseStore } from '@/storejs/warehouseStore'


//页面跳转获取数据
const warehouseStore = useWarehouseStore()
const othwr_codego = ref(warehouseStore.othwr_code) 
// 仓库库区
const Warhouse_zone = ref([]);
// 库位
const Warehouse_location = ref([]);

// 入库类型
const options = ref([])

let othwrAdd = {
    othwr_id: 0, // 新增ID字段用于修改
    othwr_type: "", // 入库类型
    othwr_code: "", // 入库单号
    othwr_wkeep: localStorage.getItem('userLName'), // 入库员
    othwr_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'), // R库时间
    othwr_status: 1, // 入库状态
    warehouse_code: "",
    warehouse_name: "",
    zone_code: "",
    zone_name: "",
    othwr_audit_by: "", // 审核人
    othwr_audit_time: "", // 审核时间
    othwr_audit_statua: 0, // 审核状态
    del_flag: '0', // 删除状态
    create_by: localStorage.getItem('userLName'), // 创建人
    create_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'), // 创建时间 
    update_by: localStorage.getItem('userLName'), // 修改人
    update_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'), // 修改时间 
}

// 模态对象
const othwr_order = reactive({ ...othwrAdd })

const ruleFormRef = ref(null)
const rules = reactive({});
//判断是否可以编辑
const InsertDrr=ref(false);

// 仓库名称查询
const Weahouse = ref([]);

const userOptions = ref([])
const deptOptions = ref([])
const customerOptons = ref([])
const customer_name = ref("")
const dialogTableVisible = ref(false)
const productData = ref([])
const currentPage = ref(1)
const pageSize = ref(5)
const pageCount = ref(0)

const productName = ref("")
const dict_code = ref("0")
const measureOptios = ref([])
const multipleTableRef = ref(null); // 表格引用

const selectedProducts = ref([]); // 存储选中的产品

const selectedTable = ref(null); // 表格引用
const selectedRows = ref([]); // 存储选中的数据
const selectedData = ref([]); // 最终确认选择的数据
const attributeOptios = ref([])
const sale_total_qty = ref(0) // 记录销售总数
const sale_total_price = ref(0) // 记录销售总额
const cost_total_proce = ref(0) // 记录产品成本总额
const router = useRouter()

var isDisabledlocation = ref();//下拉框禁用

watch(selectedData, (newVal) => {
    // 每次计算时清空累加
    sale_total_qty.value = 0
    sale_total_price.value = 0
    cost_total_proce.value = 0
    newVal.forEach(row => {
        if (isNaN(Number(row.sale_qty))) {
            ElMessage.warning('入库数量必须是数字');
            row.sale_qty = 0;
        }

        // 验证销售单价
        if (isNaN(Number(row.pro_sale_price))) {
            ElMessage.warning('入库单价必须是数字');
            row.pro_sale_price = 0;
        }

        if (row.sale_qty > row.stock_numder) {
            ElMessage.warning('入库数量不能大于当前库存');
            row.sale_qty = row.stock_numder
        }

     


        if (row.inventory_numder<=0){
                
        }else{
            if (row.sale_qty > row.inventory_numder) {
                ElMessage.warning('入库数量不能大于未入库数量');
                row.sale_qty = row.inventory_numder
            }
        }

        row.pro_total_amount = Number((row.sale_qty || 0) * (row.pro_sale_price || 0)).toFixed(2);
        row.pro_total_cost = Number((row.sale_qty || 0) * (row.pro_cost_price || 0)).toFixed(2);

        sale_total_qty.value += Number(row.sale_qty)
        sale_total_price.value += Number(row.pro_total_amount)
        cost_total_proce.value += Number(row.pro_total_cost)
    });
}, { deep: true });

// 点击修改按钮
async function handleUpdate() {
    try {
        // 1. 计算入库状态
        let allCompleted = true;
        let anyPartial = false;

        // 遍历所有明细项计算状态
        for (const item of selectedData.value) {
            const qty = Number(item.sale_qty) || 0;
            const inventoryQty = Number(item.inventory_numder) || 0;

            if (qty < inventoryQty) {
                anyPartial = true;
                allCompleted = false;
            } else if (qty !== inventoryQty) {
                allCompleted = false;
            }
        }

        // 设置入库状态
        if (allCompleted) {
            othwr_order.othwr_status = 1; // 全部入库
        } else if (anyPartial) {
            othwr_order.othwr_status = 2; // 部分入库
        } else {
            othwr_order.othwr_status = 0; // 未入库
        }

        // 更新修改人和修改时间
        othwr_order.update_by = localStorage.getItem('userLName');
        othwr_order.update_time = dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ');

        // 4. 转换明细数据 - 修复新增明细的ID问题
        const detailList = selectedData.value.map(item => ({
            // 对于新增明细，ID必须设为0
            othwrproddtl_id: item.othwrproddtl_id === 0 ? 0 : (item.othwrproddtl_id || 0),
            Othwr_id: othwr_order.othwr_id,
            Pro_name: item.stock_name,
            Pro_code: item.pro_code,
            Pro_brand: item.pro_brand,
            unitmeas_id: String(item.dict_code || ""),
            Othwrproddtl_numder: Number(item.sale_qty),
            Inventory_numder: Number(item.inventory_numder) || 0,
            Pro_model: item.stock_model,
            othwrproddtl_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
            othwrproddtl_yuan: localStorage.getItem('userLName'),
            location_code: item.location_code ? item.location_code.replace(/\r\n/g, "") : "",
            location_name: item.location_name,
            pro_cost_price: Number(item.pro_cost_price),
            pro_sale_price: Number(item.pro_sale_price)
        }));

        // 2. 发送更新请求 - 修正数据结构以匹配后端
        const response = await axios.put(
            "http://localhost:5181/api/Inv_othwr/Inv_othwr_Update",
            {
                inv_OthwrUpdateDto: {
                    Othwr_id: othwr_order.othwr_id,
                    Othwr_type: othwr_order.othwr_type,
                    Othwr_code: othwr_order.othwr_code,
                    Othwr_wkeep: othwr_order.othwr_wkeep,
                    Othwr_time: othwr_order.othwr_time,
                    Othwr_status: othwr_order.othwr_status,
                    Warehouse_code: othwr_order.warehouse_code,
                    Warehouse_name: othwr_order.warehouse_name,
                    Zone_code: othwr_order.zone_code,
                    Zone_name: othwr_order.zone_name,
                    Update_by: othwr_order.update_by,
                    Update_time: othwr_order.update_time
                },
                inv_Othwrproddtls: detailList
            },
            {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }
        );

        if (response.data > 0) {
            ElMessage.success("修改成功");
            //清空数据
            
            selectedData.value = [];
            // 7. 关闭页面
            handleClose();
        } else {
            ElMessage.error("修改失败");
        }
    } catch (error) {
        console.error("修改出错:", error);
        ElMessage.error("修改过程中发生错误: " + (error.response?.data || error.message));
    }
}

// 加载修改的数据
 function loadEditData() {
 
     axios.get("http://localhost:5181/api/Inv_othwr/inv_othwr_Select_Weahouse",{
        params: {
             Othwr_code: othwr_codego.value
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
     }).then((res) => { 
         const mainData = res.data[0];

         // 填充主表数据
         Object.assign(othwr_order, {
             othwr_id: mainData.othwr_id,
             othwr_code: mainData.othwr_code,
             othwr_type: mainData.othwr_type,
             othwr_wkeep: mainData.othwr_wkeep,
             othwr_time: mainData.othwr_time,
             othwr_status: mainData.othwr_status,
             othwr_audit_by: mainData.othwr_audit_by,
             othwr_audit_time: mainData.othwr_audit_time,
             othwr_audit_statua: mainData.othwr_audit_statua,
             warehouse_code: mainData.warehouse_code,
             warehouse_name: mainData.warehouse_name,
             zone_code: mainData.zone_code,
             zone_name: mainData.zone_name,
             create_by: mainData.create_by,
             create_time: mainData.create_time,
             update_by: mainData.update_by,
             update_time: mainData.update_time
         });

         // 根据选择的仓库编码去给库位赋值
         axios.get("http://localhost:5181/api/Db_warehouse_zone/warehouse_zone", {
             params: {
                 warehouse_code: othwr_order.warehouse_code
             },
             headers: {
                 authorization: `Bearer ${localStorage.getItem('token')}`
             }
         }).then((result) => {
             Warhouse_zone.value = result.data;
         });

         // 获取库位信息
         getWarehouse_location(othwr_order.zone_code);
       

         // 加载产品明细
         loadProductDetails();
     }).catch((res) => { 
        console.log(res)
     })
}


//function getSelect


// 加载产品明细数据
function loadProductDetails() {
    axios.get("http://localhost:5181/api/Inv_othwr/inv_OthwrproddtlSelecControllert", {
        params: {
            Othwr_code: othwr_order.othwr_code
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then(async (result) => {
        const tempData = [];

        // 遍历每个产品获取库存
        for (const item of result.data) {
            
            //获取当前产品的库存
            // const stockNumber = await StockSelect(
            //     othwr_order.warehouse_code,
            //     item.pro_code
            // );

            // 构建产品对象
            tempData.push({
                ...item,
                stock_name: item.pro_name,
                stock_model: item.pro_model,
                dict_code: item.unitmeas_id,
                sale_qty: item.othwrproddtl_numder,
                //stock_numder: stockNumber,//库存数量
                pro_sale_price: item.pro_sale_price || 0,//售价
                pro_cost_price: item.pro_cost_price || 0,//成本价
                pro_total_amount: 0,
                pro_total_cost: 0,
                location_code: item.location_code,//库位
                location_name: item.location_name,//库位名称
              
                //关联单号
                stock_entry_no: item.stock_entry_no,
                              
            });
          
        }

        selectedData.value = tempData;
       // console.log(selectedData.value);
        //isDisabledlocation.value = true;
    }).catch((error) => {
        console.error("加载产品明细失败:", error);
        ElMessage.error('加载产品明细失败');
    });
}




//根据仓库编码和产品编码查询库存信息
function StockSelect(Waarehouse_code, Pro_code) {
    return axios.get("http://localhost:5181/api/Inv_Stock/GetinvStock", {
        params: {
            weahouse_code: Waarehouse_code,
            por_code: Pro_code,
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((res) => {
        return res.data;
    }).catch((res) => {
        console.log(res);
    })
}

function getUser() {
    axios.get("http://localhost:5181/api/User/GetUsers", {
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        userOptions.value = result.data
    }).catch((err) => {
        console.info(err)
    });
}

function getDept() {
    axios.get("http://localhost:5181/api/Dept/Get_Dept_Trees", {
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        deptOptions.value = convertToTreeOptions(result.data)
    }).catch((err) => {
        console.info(err)
    });
}



// 查询客户信息
function getCustomer() {
    axios.get("http://localhost:5181/api/Sinv_Customer/Sinv_CustomerByName", {
        params: {
            name: customer_name.value
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        customerOptons.value = result.data
    }).catch((err) => {
        console.info(err)
    });
}

// 把二维数据转换为结构数据
const convertToTreeOptions = (items) => {
    return items.map(item => ({
        value: item.dept_id,
        label: item.dept_name,
        children: item.children && item.children.length > 0
            ? convertToTreeOptions(item.children)
            : []
    }))
}

// 获取下拉选项数据
function getClassify() {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
            dict_type: "sys_inv_othwr"
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        options.value = result.data
    }).catch((err) => {
        console.info(err)
    });
}

// 选择入库事件触发
const handleSelectChange = (selectedValue) => {
    const selectedItem = Weahouse.value.find(item => item.warehouse_code === selectedValue);
    othwr_order.warehouse_name = selectedItem.warehouse_name;


    // 清空库区、库位
    othwr_order.zone_code = "";
    othwr_order.zone_name = "";
    selectedData.value.forEach(item => {
        item.location_code = "";
        item.location_name = "";
    });

    // 根据选择的仓库编码去给库位赋值
    axios.get("http://localhost:5181/api/Db_warehouse_zone/warehouse_zone", {
        params: {
            warehouse_code: selectedValue
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        Warhouse_zone.value = result.data;
    })
};

// 入库类型选择事件触发
const handleSelecttype = (value) => {
    const selectedItem = options.value.find(item => item.dict_value == value)
    othwr_order.othwr_type = selectedItem.dict_value;
}

// 选择入库库区的时触发
const handleSzone = (value) => {
    const selectedItemzone = Warhouse_zone.value.find(item => item.zone_code == value)
    othwr_order.zone_name = selectedItemzone.zone_name;


    // 清空库位
    selectedData.value.forEach(item => {
        item.location_code = "";
        item.location_name = "";
    });

    //下拉框禁用解除
    isDisabledlocation.value = false;
    //获取库位
    getWarehouse_location(value);
}

//获取库位的下拉框的时数据
function getWarehouse_location(value) { 

    axios.get("http://localhost:5181/api/Db_warehouse_location/warehouse_location", {
        params: {
            zone_code: value
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        Warehouse_location.value = result.data;
    }).catch((err) => {
        console.info(err)
    })
}


//选择入库库位的触发事件
const locationEndit = (value, row) => {
    // 1. 直接更新当前行的数据
    row.location_code = value; // 确保location_code更新
    const selectedItem = Warehouse_location.value.find(item => item.location_code === value);
    row.location_name = selectedItem ? selectedItem.location_name : '';

    if (!selectedItem) {
        ElMessage.error('未找到该库位信息');
        return;
    }

    // 2. 获取可用容量
    const availableCapacity = selectedItem.location_available_capacity;

    // 3. 计算当前库位的入库总量
    const totalQty = selectedData.value
        .filter(item => item.location_code === value)
        .reduce((sum, item) => sum + Number(item.sale_qty || 0), 0);

    // 4. 检查容量是否足够
    if (totalQty > availableCapacity) {
        ElMessage.error(`库位容量不足！可用：${availableCapacity}，已分配：${totalQty}`);
        // 5. 回滚选择
        row.location_code = '';
        row.location_name = '';
    }
};

function productAdd() {
    dialogTableVisible.value = true
}

// 移除选中的table控件数据
const productDel = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要移除的数据');
        return;
    }

    const selectedCodes = selectedRows.value.map(item => item.pro_code);
    selectedData.value = selectedData.value.filter(
        item => !selectedCodes.includes(item.pro_code)
    );

    if (selectedTable.value) {
        selectedTable.value.clearSelection();
    }

    selectedRows.value = [];
};

// 分页查询产品库存信息
function productFill() {
    axios.get("http://localhost:5181/api/Db_warehouse/GetInv_Stock", {
        params: {
            productName: productName.value,
            dict_code: dict_code.value,
            currentPage: currentPage.value,
            pageSize: pageSize.value
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        productData.value = result.data
    }).catch((err) => {
        console.info(err)
    });
}

// 查询产品库存总数
function productCount() {
    axios.get("http://localhost:5181/api/Db_warehouse/Inv_StockCount", {
        params: {
            productName: productName.value,
            dict_code: dict_code.value
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        pageCount.value = result.data
    }).catch((err) => {
        console.info(err)
    });
}

function handleSizeChange(val) {
    pageSize.value = val;
    productFill();
}

function handleCurrentChange(val) {
    currentPage.value = val;
    productFill();
}

// 查询计量单位
function getMeasure() {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
            dict_type: "db_measure"
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        measureOptios.value = result.data
        measureOptios.value = [{
            dict_value: "0", dict_label: "请选择单位"
        }, ...result.data]
    }).catch((err) => {
        console.info(err)
    });
}

// 根据计量单位id返回计量单位名称
function measureValue(row) {
    if (!row) return "无";
    const parentDept = measureOptios.value.find((sex) => sex.dict_value == row);
    return parentDept ? parentDept.dict_label : "无";
}

// 查询产品属性
function getAttribute() {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
            dict_type: "db_pro_attribute"
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        attributeOptios.value = result.data
    }).catch((err) => {
        console.info(err)
    });
}

// 根据产品属性id返回产品属性名称
function attributeValue(row) {
    if (!row) return "无";
    const parentDept = attributeOptios.value.find((sex) => sex.dict_value == row);
    return parentDept ? parentDept.dict_label : "无";
}

// 根据选择条件查询产品库存信息
function productEedit() {
    productFill()
    productCount()
}

// 重置条件查询
function productReaslt() {
    productName.value = ""
    dict_code.value = "0"
    productFill()
    productCount()
}

// 表格选择变化时的处理函数
const handleSelectionChange = (val) => {
    selectedProducts.value = val;
};

// 点击确定存储选择的产品数据
const handleConfirmSelection = () => {
    selectedData.value = [...selectedData.value, ...selectedProducts.value.map(item => ({
        ...item,
        sale_qty: Number(0), // 初始化销售数量为0
        pro_total_amount: Number(0).toFixed(2), // 销售总金额
        pro_total_cost: Number(0).toFixed(2), // 成本合计
        pro_sale_price: Number(item.pro_sale_price || 0).toFixed(2), // 格式化销售单价
        pro_cost_price: Number(item.pro_cost_price || 0).toFixed(2), // 格式化成本单价
    }))] // 保存选择的产品数据
    dialogTableVisible.value = false
    multipleTableRef.value.clearSelection() // 清空当前选择
}

// 表格选择变化时处理数据
const handleSelectedChange = (val) => {
    selectedRows.value = val;
};

// 判断以添加过的产品数据不能再次添加
const isDisabled = (row) => {
    return !selectedData.value.some(item => item.pro_code === row.pro_code);
};

// 退出页面并删除当前页面的标签页
const closeTab = inject('closeTab'); // 注入关闭方法
function handleClose() {
    const targetPath = "/main/Inv/OtherWarehouseReceipts";

    if (closeTab) {
        closeTab(); // 调用父组件提供的关闭方法
    }

    // 添加目标标签页（如果不存在）
    const tabs = inject('editableTabs');
    if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
        tabs.value.push({
            title: "销售订单",
            name: targetPath,
            path: targetPath
        });
    }

    // 跳转并激活目标标签页
    const activeTab = inject('editableTabsValue');
    if (activeTab) {
        activeTab.value = targetPath;
    }

    router.push(targetPath);
}

// 查询仓库信息
function WeahousesSelect() {
    axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBySelect", {
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
    }).then((res) => {
        Weahouse.value = res.data;
    }).catch((res) => {
        console.log(res)
    })
}

onMounted(() => {
  // 加载修改数据
    loadEditData();

    getUser();
    getDept();
    getMeasure();
    getAttribute();
    getCustomer();
    productFill();
    productCount();
    getClassify();
    WeahousesSelect();
});
</script>

<style scoped>
.goods-add-form {
    padding: 20px;
    background-color: #fff;
}

.section {
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
}

.filter-section {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: 20px;
    height: 7%;
    align-items: center;
    width: 80.5%;
    background-color: #ffffff;
    justify-content: flex-end;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding-right: 20px

}

.order-input :deep(.el-input__inner) {
    cursor: pointer;
    background-color: #f5f7fa;
}

.order-input:hover :deep(.el-input__inner) {
    border-color: #c0c4cc;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    padding-top: 15px;
    border-top: 1px solid #ebeef5;
}

.el-table--enable-row-hover .el-table__body tr:hover>td {
    background-color: #f5f7fa !important;
    cursor: pointer;
}
</style>